package com.example.commonlib.commonutil;

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;

import com.example.commonlib.base.MyApplication;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;


/**
 * Created by Asus on 2018/5/14.
 */

public class PerlyStoreParcelableTool {
    public static final String TAG = "AESUtils";
    /**
     * 写方法
     */
    public static void saveParce(Object object) {
        FileOutputStream fos;
        try {
            fos = MyApplication.isIntance.openFileOutput(TAG,
                    Context.MODE_PRIVATE);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            Parcel parcel = Parcel.obtain();
            parcel.writeParcelable((Parcelable) object, 0);

            bos.write(parcel.marshall());
            bos.flush();
            bos.close();
            fos.flush();
            fos.close();
            parcel.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读方法
     */
    public static Object loadParce() {
        FileInputStream fis;
        try {
            fis = MyApplication.isIntance.openFileInput(TAG);
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            Parcel parcel = Parcel.obtain();
            parcel.unmarshall(bytes, 0, bytes.length);
            parcel.setDataPosition(0);

            Object object = parcel.readParcelable(Object.class.getClassLoader());
            fis.close();
            parcel.recycle();
            return object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
